#!/usr/bin/env python

# (c) 2007-2011 Helsinki University of Technology and University of Helsinki
# Licensed under the MIT license; see LICENSE.txt for more information.

from worker import Worker
from document import Document
from rdf import *
import os
import os.path
import sys

# maps output format to file extension
# those not mentioned have the same extension as the format name
EXTMAP = {
  'pretty-xml': 'rdf',
  'xml': 	'rdf',
  'turtle': 	'ttl',
}

class Store (Worker):
  def __init__(self, session):
    Worker.__init__(self, session.getFatalEvent())
    self._session = session

    if self._session.getStore():
      # make sure all paths exist
      outputdir = self._session.getConfig().getOutputDir()
      source = self._session.getSource().getName()

      if not os.path.exists(outputdir):
        os.mkdir(outputdir)
      
      if not os.path.exists(outputdir + "/" + source):
        os.mkdir(outputdir + "/" + source)
  
    # create empty metadata store
    self._metadata = getMetadataGraph(self._session.getSource().getName())
  
  def get_extension(self, format):
    return EXTMAP.get(format, format)

  def process(self, doc):
    self._metadata += doc.getMetadataGraph()
    # copy namespace prefixes as well
    for prefix, uri in doc.getMetadataGraph().namespaces():
      self._metadata.namespace_manager.bind(prefix, uri)
    
    doc.releaseData()
    doc.setCompleted('store')
    doc.log('SUCC', 'store', 'Successfully stored document metadata')
    doc.processingFinished()
    return True
  
  def finish(self):
    # store metadata in $outputdir/$source.rdf
    if self._session.getStore():
      outdir = self._session.getConfig().getOutputDir()
      name = self._session.getSource().getName()
      format = self._session.getSource().getOutputFormat()
      ext = self.get_extension(format)
      metadatafile = "%s/%s.%s" % (outdir, name, ext)
      
      if os.path.exists(metadatafile) and self._session.getDelete():
        # create a list of files to delete
        meta = file(metadatafile, 'r')
        old = getGraph()
        parsefmt = format
        # rdflib doesn't have a separate turtle parser, use n3 for that
        if parsefmt == "turtle": parsefmt="n3"
        old.parse(meta, format=parsefmt)
        meta.close()
        
        delete = getMetadataGraph(name + "-delete")
        for pub in old.subjects(RDF.type, TS.Publication):
          if (pub, RDF.type, TS.Publication) not in self._metadata:
            delete.add((pub, RDF.type, TS.DeletedPublication))
        
        delfile = "%s/%s-delete.%s" % (outdir, name, ext)
        delf = file(delfile, 'w')
        delete.serialize(destination=delf, format=format)
        delf.close()

      meta = file(metadatafile, 'w')
      self._metadata.serialize(destination=meta, format=format)
      meta.close()
    # free some memory
    del self._metadata
